package org.feng.datasource;

import org.springframework.boot.jdbc.DataSourceBuilder;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 数据源池
 *
 * @author pine
 * @version v1.0
 * @since 2025-06-07 17:02
 */
public class DataSourcePool {

    private static final Map<Object, Object> DATA_SOURCE_POOL = new ConcurrentHashMap<>();

    private static final Map<String, DataSourceProperties> DATASOURCE_PROPERTIES_POOL = new ConcurrentHashMap<>();


    public static void setDataSource(String merchant, DataSourceProperties dataSourceProperties) {
        DATA_SOURCE_POOL.put(merchant, buildDataSource(dataSourceProperties));
    }

    public static DataSource getDataSource(String merchant) {
        return (DataSource) DATA_SOURCE_POOL.get(merchant);
    }


    public static Map<Object, Object> getDataSourcePool() {
        return DATA_SOURCE_POOL;
    }

    public static void setDatasourceProperties(String merchant, DataSourceProperties dataSourceProperties) {
        DATASOURCE_PROPERTIES_POOL.put(merchant, dataSourceProperties);
    }

    public static DataSourceProperties getDatasourceProperties(String merchant) {
        return DATASOURCE_PROPERTIES_POOL.get(merchant);
    }

    public static Map<String, DataSourceProperties> getDatasourcePropertiesPool() {
        return DATASOURCE_PROPERTIES_POOL;
    }


    public static void removeDataSource(String merchant) {
        DATA_SOURCE_POOL.remove(merchant);
    }

    public static void removeDatasourceProperties(String merchant) {
        DATASOURCE_PROPERTIES_POOL.remove(merchant);
    }

    public static DataSource buildDataSource(DataSourceProperties dataSourceProperties) {
        return DataSourceBuilder.create()
                .driverClassName(dataSourceProperties.getDriverClassName())
                .url(dataSourceProperties.getJdbcUrl())
                .username(dataSourceProperties.getUsername())
                .password(dataSourceProperties.getPassword())
                .build();
    }
}
